<template>
  <el-upload
    class="upload-demo"
    drag
    :action="action"
    multiple
    :before-upload="beforeUpload"
    :data="data"
    :on-success="handleSuccess"
    :file-list="list"
    :on-remove="handleRemove"
    :on-preview="handlePreview"
  >
    <i class="el-icon-upload" />
    <div class="el-upload__text">
      将文件拖到此处，或
      <em>点击上传</em>
    </div>
    <div slot="tip" class="el-upload__tip">文件不能超过20M</div>
  </el-upload>
</template>

<script>
import API from '@/api/common/adjunct'
export default {
  name: 'Adjunct',
  props: {
    table: {
      type: String,
      default: ''
    },
    pk: {
      type: Number,
      default: 0
    },
    request_id: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      action: process.env.VUE_APP_BASE_API + '/v1/knowledgeAdjunctAdd',
      list: []
    }
  },
  computed: {
    data() {
      return {
        table: this.table,
        id: this.pk,
        request_id: this.request_id
      }
    }
  },
  watch: {
    pk() {
      this.index()
    },
    table() {
      this.index()
    },
    request_id() {
      this.index()
    },
    list(newVal) {
      this.$emit('change', newVal)
    }
  },
  created() {
    this.index()
  },
  methods: {
    index() {
      API.knowledgeIndex(this.request_id).then(response => {
        this.list = response.data
      })
    },
    handleSuccess(res) {
      console.log(res)
      this.list.push(res.data)
    },
    beforeUpload(file) {
      const isLt20M = file.size / 1024 / 1024 < 20
      if (!isLt20M) {
        this.$message.error('文件大小不能超过 20MB!')
      }
      return isLt20M
    },
    handlePreview(file) {
      console.log(file.path)
      window.open(file.path, 'blank')
    },
    handleRemove(file) {
      API.delete(file.id)
    }
  }
}
</script>

<style>
  .upload-demo{
    width: 100%;
  }
  .el-upload{
    width: 100%;
  }
</style>
